package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.AreaCategoryManager;
import com.anne.fish.model.AreaCategory;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class AreaCategoryAction extends BaseAction implements Preparable {
    private AreaCategoryManager areaCategoryManager;
    private List areaCategories;
    private AreaCategory areaCategory;
    private Long id;
    private String query;

    public void setAreaCategoryManager(AreaCategoryManager areaCategoryManager) {
        this.areaCategoryManager = areaCategoryManager;
    }

    public List getAreaCategories() {
        return areaCategories;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String areaCategoryId = getRequest().getParameter("areaCategory.id");
            if (areaCategoryId != null && !areaCategoryId.equals("")) {
                areaCategory = areaCategoryManager.get(new Long(areaCategoryId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        areaCategories = areaCategoryManager.search(query, AreaCategory.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public AreaCategory getAreaCategory() {
        return areaCategory;
    }

    public void setAreaCategory(AreaCategory areaCategory) {
        this.areaCategory = areaCategory;
    }

    public String delete() {
        areaCategoryManager.remove(areaCategory.getId());
        saveMessage(getText("areaCategory.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            areaCategory = areaCategoryManager.get(id);
        } else {
            areaCategory = new AreaCategory();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (areaCategory.getId() == null);

        areaCategoryManager.save(areaCategory);

        String key = (isNew) ? "areaCategory.added" : "areaCategory.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}